import datetime


class DataChecker:
    def __init__(self, context):
        self.context = context

    def log_error_and_set_response(self, message):
        self.context.app.logger.error(message)
        self.context.response_message = message
        return False

    def check_data_existence(self, data, key, message):
        if key not in data or not data[key]:
            return self.log_error_and_set_response(message)
        return True

    def check_list_items(self, data_list, keys, message_template):
        for item in data_list:
            for key in keys:
                if not item.get(key):
                    return self.log_error_and_set_response(message_template.format(key))
        return True

    def in_data_check(self):
        data = self.context.in_data
        try:
            # 时间窗配置信息
            if not self.check_data_existence(data, 'timeWindowConfigList', "[TW] 时间窗配置列表为空"):
                return

            # 自制装车信息
            if not self.check_list_items(data['wopsSelfProductVehiclePlanList'],
                                         ['deliverFactoryCode', 'planBegin', 'planEnd', 'vehicleNum'],
                                         "[TW] 自制装车列表  [{}] 为空"):
                return

            # 时间窗信息列表
            if not self.check_data_existence(data, 'timeWindowList', "[TW] 时间窗信息列表 为空"):
                return

            for windows in data['timeWindowList']:
                for key in ['planBegin', 'planEnd']:
                    if not windows.get(key):
                        self.log_error_and_set_response(f"[TW] 时间窗信息列表  [{key}] 为空")
                        return
                    try:
                        datetime.datetime.strptime(windows[key].replace("T", " "), "%Y-%m-%d %H:%M:%S")
                    except ValueError:
                        self.log_error_and_set_response(
                            f"[TW] 时间窗信息列表 时间格式转化失败 需要格式为 %Y-%m-%d %H:%M:%S ，提供格式为 {windows[key]}")
                        return

            # lpn列表
            if not self.check_data_existence(data, 'lpnListByOrder', "[TW] lpn列表 为空"):
                return

            if not self.check_list_items(data['lpnListByOrder'], ['cCompany'], "[TW] lpn列表  [{}] 为空"):
                return

        except KeyError as e:
            self.log_error_and_set_response(f"[TW] 获取数据 {e} 失败")
            return

    def config_data_check(self, dis_value, port_config_list, port_assignment_map, port_assignment_data):
        try:
            for item in port_assignment_data:
                key = item['code'].split('-')[0]
                value = [int(item['code'].split('-')[1]), int(item['value'])]
                port_assignment_map[key].append(value)
        except Exception as ex:
            self.context.app.logger.error(ex)
            self.log_error_and_set_response(f"[TW] 获取出货口配置信息失败")

        if dis_value is None:
            self.log_error_and_set_response("[TW] 打折系数为空")
            return

        try:
            self.check_list_items(port_config_list, ['total_port_number', 'delivery_pack_type', 'flow'],
                                  '[TW] wops_delivery_port_config [{}] 为空')
        except KeyError as e:
            self.log_error_and_set_response(f"[TW] 获取出货口配置信息: {e} 失败")
            return
